{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Minimum Removals for Valid Parenthesis\n",
    "\n",
    "[原题](https://mp.weixin.qq.com/s/16_ZTok-SRZkXTWMEUcuYg)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "You are given a string of parenthesis. Return the minimum number of parenthesis that would need to be removed in order to make the string valid. \"Valid\" means that each open parenthesis has a matching closed parenthesis."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example\n",
    "\n",
    "```text\n",
    "Input: \"()())()\"\n",
    "Output: 1\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def count_invalid_parenthesis(string):\n",
    "    ''' Main Algorithm '''\n",
    "    stack = []\n",
    "    for ch in string:\n",
    "        if ch == '(' or (ch == ')' and stack == []):\n",
    "            stack.append(ch)\n",
    "        elif ch == ')' and stack != []:\n",
    "            stack.pop()\n",
    "    return len(stack)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "print(count_invalid_parenthesis(\"()())()\"))\n",
    "# 1"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
